import { updateIndex, getIndex } from '../services/index';
import { systemConstants } from 'src/utils/constants';
import pathToRegexp from 'path-to-regexp';
import { transform } from 'src/utils';

export default {
  namespace: 'createIndex',
  state: {
    // will do
  },
  subscriptions: {
    setup({ history, dispatch }) {
      return history.listen(({ pathname }) => {
          const match = pathToRegexp('/editIndex/:id').exec(pathname);
          if (match) {
            dispatch({ type: 'getIndex', payload: match[1] });
          }
          else {
            dispatch({
              type: 'initIndex',
              payload: {
                basicInfo: {},
                fields: [],
              }
            });
          }
        }
      );
    }
  },
  effects: {
    * getIndexs ({ payload, }, { call, put, select }) {
        const { data, error } = yield call(getIndex, {id: payload});
        yield put({
          type: 'initIndex',
          payload: data,
        });
      },

    * updateIndexs ({ payload, }, { call, put }) {
        const { data, error } = yield call(updateIndex, payload);

        yield put({
          type: 'initIndex',
          payload: data,
        });
      },
  },
  reducers: {
    initIndex(state, action) {
      return {
        ...state,
        basicInfo: action.payload.basicInfo,
        fields: transform.addKey(action.payload.fields),
      }
    },

  },
}
